package com.github.ilioili.justdoit.components.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.common.AppBaseActivity;
import com.github.ilioili.justdoit.common.config.AnimationConfig;
import com.github.ilioili.justdoit.util.CompatUtil;
import com.github.ilioili.justdoit.widget.CircleAnimationFrame;
import com.github.ilioili.justdoit.widget.MonthView;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.Layout;

import java.util.Calendar;
import java.util.LinkedList;

/**
 * Created by hantuo on 16/5/23.
 */
@Layout(R.layout.activity_pick_date)
public class PickDateActivity extends AppBaseActivity {

    public static final int START_YEAR = 2010;
    public static final int END_YEAR = 2022;
    private int curPageYear;
    private int curPageMonth;
    private int curPageDay;
    private Calendar today;

    private LinkedList<MonthView> monthViews = new LinkedList();
    private static OnDateSelectListener listener;
    @Id(R.id.viewPager)
    private ViewPager viewPager;
    @Id(R.id.tv_year)
    private TextView tvYear;
    @Id(R.id.tv_day)
    private TextView tvDay;
    @Id(R.id.tv_week)
    private TextView tvWeek;
    private CircleAnimationFrame circleAnimationFrame;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        circleAnimationFrame = (CircleAnimationFrame) findViewById(R.id.circle_animation_frame);
        setViewPager();
        today = Calendar.getInstance();
        setTimeToToday();
        circleAnimationFrame.expand(CircleAnimationFrame.Gravity.Center, AnimationConfig.MEDIUM);
    }

    private void setTimeToToday() {
        curPageMonth = today.get(Calendar.MONTH);
        curPageYear = today.get(Calendar.YEAR);
        curPageDay = today.get(Calendar.DAY_OF_MONTH);
        viewPager.setCurrentItem((curPageYear - START_YEAR) * 12 + curPageMonth);
        tvYear.setText("" + curPageYear);
        tvDay.setText(curPageYear + "." + (curPageMonth + 1) + "." + curPageDay);
        tvWeek.setText(getResources().getStringArray(R.array.WeekDay)[today.get(Calendar.DAY_OF_WEEK)-1]);
    }


    private MonthView getMonthView(final Activity activity) {
        MonthView monthView = monthViews.poll();
        if (null == monthView) {
            final MonthView mv = new MonthView(activity);
            mv.setAdapter(new MonthView.Adapter() {
                @Override
                public View getView(View view, int year, int month, final int day) {
                    final TextView textView;
                    if (null == view) {
                        view = LayoutInflater.from(activity).inflate(R.layout.day_cell_dialog, mv, false);
                    }
                    textView = (TextView) view.findViewById(R.id.textView);
                    textView.setText(day + "");
                    if (curPageDay != day) {
                        textView.setSelected(false);
                        textView.setTextColor(CompatUtil.getColor(PickDateActivity.this, R.color.colorPrimary));
                    } else {
                        textView.setSelected(true);
                        textView.setTextColor(Color.WHITE);
                    }
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            curPageDay = day;
                            tvDay.setText(curPageYear + "." + (curPageMonth + 1) + "." + curPageDay);
                            Calendar calendar = Calendar.getInstance();
                            calendar.set(curPageYear, curPageMonth, curPageDay);
                            tvWeek.setText(getResources().getStringArray(R.array.WeekDay)[calendar.get(Calendar.DAY_OF_WEEK)-1]);
                            viewPager.getAdapter().notifyDataSetChanged();
                        }
                    });
                    return view;
                }
            });
            monthView = mv;
        }
        return monthView;
    }

    private void setViewPager() {
        final PagerAdapter adapter = new PagerAdapter() {
            @Override
            public void startUpdate(ViewGroup container) {
                viewPager.requestLayout();//解决HeadTabPagerWrappper 的 BUG 导致无法自动刷新问题
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
                monthViews.add((MonthView) object);
            }


            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                int year = START_YEAR+position / 12;
                int month = position % 12 + 1;
                MonthView monthView = getMonthView(PickDateActivity.this);
                monthView.setMonth(year, month - 1);
                container.addView(monthView);
                return monthView;
            }


            @Override
            public int getCount() {
                return (END_YEAR - START_YEAR) * 12;
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        };
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            Calendar calendar = Calendar.getInstance();

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                curPageYear = position / 12 + START_YEAR;
                curPageMonth = position % 12;
                calendar.set(Calendar.YEAR, curPageYear);
                calendar.set(Calendar.MONTH, curPageMonth);
                if (curPageDay > calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                    curPageDay = 1;
                    adapter.notifyDataSetChanged();
                }
                tvYear.setText("" + curPageYear);
                tvDay.setText(curPageYear + "." + (curPageMonth + 1) + "." + curPageDay);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void onClickToday(View v) {
        setTimeToToday();
    }

    public void onClickPreYear(View v) {
        curPageYear--;
        if (curPageYear == START_YEAR - 1) {
            curPageYear = START_YEAR;
        }
        tvYear.setText("" + curPageYear);
        viewPager.setCurrentItem((curPageYear - START_YEAR) * 12 + curPageMonth);
    }

    public void onClickNextYear(View v) {
        curPageYear++;
        if (curPageYear == END_YEAR) {
            curPageYear = END_YEAR - 1;
        }
        tvYear.setText("" + curPageYear);
        viewPager.setCurrentItem((curPageYear - START_YEAR) * 12 + curPageMonth);
    }

    public interface OnDateSelectListener {
        void onDateSelect(int year, int month, int day);
    }


    public void onClickCancel(View v) {
        circleAnimationFrame.collapse(CircleAnimationFrame.Gravity.Center, AnimationConfig.MEDIUM, true, new CircleAnimationFrame.CompleteListener() {
            @Override
            public void onComplete() {
                finish();
            }
        });
    }

    public void onClickConfirm(View v) {
        listener.onDateSelect(curPageYear, curPageMonth, curPageDay);
        finish();
    }

    public static Intent newIntent(Context context, OnDateSelectListener onDateSelectListener) {
        Intent intent = new Intent(context, PickDateActivity.class);
        listener = onDateSelectListener;
        return intent;
    }

    @Override
    public void onBackPressed() {
        circleAnimationFrame.collapse(CircleAnimationFrame.Gravity.Center, AnimationConfig.MEDIUM, true, new CircleAnimationFrame.CompleteListener() {
            @Override
            public void onComplete() {
                finish();
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }
}
